package com.yf.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import io.gitee.loulan_yxq.owner.core.tool.ObjectTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    private final static String CREATE_TIME = "crtTime";
    private final static String UPDATE_TIME = "uptTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        Object createTime = getFieldValByName(CREATE_TIME, metaObject);
        Object updateTime = getFieldValByName(UPDATE_TIME, metaObject);
        LocalDateTime date = LocalDateTime.now();

        if (ObjectTool.isNull(createTime)) {
            setFieldValByName(CREATE_TIME, date, metaObject);
        }

        if (ObjectTool.isNull(updateTime)) {
            setFieldValByName(UPDATE_TIME, date, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        // 更新的时候更新时间直接修改
        setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);

        // 跟新不允许修改创建时间字段
        setFieldValByName(CREATE_TIME, null, metaObject);
    }
}